package com.files.annotation.controller;

import com.files.annotation.MyAnnotation;
import com.files.annotation.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 袁强
 * @version 2024年10月17日 21:31:30
 */
@RestController
@RequestMapping("/annotation")
public class AnnotationController {

	@RequestMapping("/test")
	@ResponseBody
	public Object test() {

		Student student = new Student();
		People people = new People("张三", 30);

		Class<? extends People> peopleClass = people.getClass();
		Field[] peopleFields = peopleClass.getDeclaredFields();
		Map<String, Object> keyValue = new HashMap<>();
		for (Field field :peopleFields) {
			String name = field.getName();
			try{
				field.setAccessible(true);
				Object value = field.get(people);
				keyValue.put(name,value);
			}catch (Exception e){
				System.err.println("获取属性值出错：" + e.getMessage());
			}
		}
		Class<? extends Student> aClass = student.getClass();
		//返回自身声明的所有字段，
		// 包括公共（public）、私有（private）、受保护（protected）和默认（包访问权限）字段，
		// 但不包括从父类或接口继承的字段
		Field[] declaredFields = aClass.getDeclaredFields();
		//返回的是类或接口中所有可访问（public）的字段，
		// 包括从父类和接口继承而来的公共字段
		Field[] fields = aClass.getFields();

		for (Field field :declaredFields) {
			Annotation[] annotations = field.getAnnotations();
			for (int i = 0; i < annotations.length; i++) {
				System.out.println(annotations[i].annotationType().getName());
			}
			//判断是否带有MyAnnotation注解
			if(field.isAnnotationPresent(MyAnnotation.class)){
				MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
				String property = annotation.property();
				System.out.println("找到带有注解的方法：" + field.getName());
				System.out.println("注解的值为：" + property);
				field.setAccessible(true);
				try{
					field.set(student,keyValue.get(property));
				}catch (Exception e){
					System.err.println("设置属性出错：" + e.getMessage());
				}
			}
		}
		return student;
	}
}
